﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.IO;
using UnityEditor;
using System.Xml.Serialization;
using static HotUpdateView;
using System;
using System.Net;

public class Package : Editor
{
    public static string luaPath = Application.dataPath + "/Lua";
    public static string tempPath = Application.dataPath + "/TempLua";

    //推送资源到服务端
    [MenuItem("Tools/Resource/PushResource")]
    static void CommandPushResource()
    {

        var _ABPath = Application.dataPath.Replace("/Assets", "");
        _ABPath = Path.Combine(_ABPath, "doc/copyBundle.bat");
        System.Diagnostics.Process pExecuteEXE = new System.Diagnostics.Process();
        pExecuteEXE.StartInfo.FileName = _ABPath;
        pExecuteEXE.Start();
        pExecuteEXE.WaitForExit(); // 无限期等待完成
        Debug.Log("-----------资源推送成功--------------");
    }


    [MenuItem("Tools/CreatAssetBundle for Android")]
    static void CreatAssetBundle()
    {
        var path = Application.dataPath.Replace("/Assets", "");
        path = Path.Combine(path, "AssetBundle");
        AssetImportHandler.SetABTagToPrefab();
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        //检查lua代码 把lua代码加上打包标签
        CreatePackageLua();
        CreatePackageFont();
        BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.Android);
        UnityEngine.Debug.Log("Android Finish!");
        CreatePackageVersion(path);
        DeleteLuaTemp();
    }

    [MenuItem("Tools/CreatAssetBundle for IOS")]
    static void BuildAllAssetBundlesForIOS()
    {
        var dirName = Application.dataPath.Replace("/Assets", "");
        dirName = Path.Combine(dirName, "AssetBundle");
        if (!Directory.Exists(dirName))
        {
            Directory.CreateDirectory(dirName);
        }
        //检查lua代码 把lua代码加上打包标签
        CreatePackageLua();
        BuildPipeline.BuildAssetBundles(dirName, BuildAssetBundleOptions.CollectDependencies, BuildTarget.iOS);
        UnityEngine.Debug.Log("IOS Finish!");
        CreatePackageVersion(dirName);
        DeleteLuaTemp();
    }

    [MenuItem("Tools/CreatAssetBundle for Win")]
    public static void CreatPCAssetBundleForwINDOWS()
    {
        var _ABPath = Application.dataPath.Replace("/Assets", "");
        _ABPath = Path.Combine(_ABPath, "AssetBundle");
        AssetImportHandler.SetABTagToPrefab();
        if (!Directory.Exists(_ABPath))
        {
            Directory.CreateDirectory(_ABPath);
        }
        Directory.CreateDirectory(_ABPath);
        //检查lua代码 把lua代码加上打包标签
        CreatePackageLua();
        CreatePackageFont();
        BuildPipeline.BuildAssetBundles(_ABPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
        CreatePackageVersion(_ABPath);
        DeleteLuaTemp();
        UnityEngine.Debug.Log("Win Finish!");
    }



    private static void DeleteLuaTemp()
    {
        if (Directory.Exists(tempPath))
        {
            Directory.Delete(tempPath, true);
        }
        AssetDatabase.Refresh();
    }

    //生成打包版本
    public static void CreatePackageVersion(string path)
    {
        DirectoryInfo directoryInfo = new DirectoryInfo(path);
        FileInfo[] fileInfos = directoryInfo.GetFiles();
        var packageVersion = new PackageVersion();
        packageVersion.version = Utils.GetTimeStamp();
        foreach (var file in fileInfos)
        {
            var _filePath = file.FullName;
            var _md5 = Utils.GetMD5String(_filePath);
            packageVersion.resList.Add(new ResVO() { md5Str = _md5, resName = file.Name });
        }

        var versionPath = Path.Combine(path, Const.VERSION_FILE_NAME);
        if (File.Exists(versionPath))
        {
            File.Delete(versionPath);
        }
        File.Create(versionPath).Close();
        TextWriter filestream = new StreamWriter(versionPath);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(PackageVersion));
        xmlSerializer.Serialize(filestream, packageVersion);
        filestream.Close();
    }


    //创建字体打包
    private static void CreatePackageFont() {
        AssetImportHandler.SetABTagToFont();
    }


    //生成LUA打包
    private static void CreatePackageLua()
    {
        var dataPath = Application.dataPath.Replace("/", @"\") + @"\TempLua\";
        //G:/projects/xlua-frmework/Assets
        if (!Directory.Exists(tempPath))
        {
            Directory.CreateDirectory(tempPath);
        }
        //把LUA里面的lua文件全部转为txt文件
        DirectoryInfo directory = new DirectoryInfo(Application.dataPath + "/Lua");
        var files = directory.GetFiles("*.lua", SearchOption.AllDirectories);

        foreach (var file in files)
        {
            var targetPath = file.FullName.Replace(@"\Lua\", @"\TempLua\");
            targetPath = targetPath.Replace(".lua", ".bytes");
            //1 转为byte
            byte[] bytes = File.ReadAllBytes(file.FullName);
            if (!Directory.Exists(Path.GetDirectoryName(targetPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
            }
            File.WriteAllBytes(targetPath, bytes);
            AssetDatabase.Refresh();
        }

        foreach (var file in files)
        {
            //G:\projects\xlua-frmework\Assets\Lua\manager\PanelManager.lua
            var targetPath = file.FullName.Replace(@"\Lua\", @"\TempLua\");
            targetPath = targetPath.Replace(".lua", ".bytes");
            //拿包名
            //给byte的lua设置打包标签
            var fullDireName = Path.GetDirectoryName(targetPath);
            var packageName = Utils.GetRelativePath(fullDireName).Replace("Assets","");
            packageName = packageName.Replace("/", "_");

            packageName = packageName.Replace("_TempLua", "");
            if (packageName == "")
            {
                packageName = "LUA_main"; 
            }
            else
            {
                packageName = "LUA" + packageName;
            }
            //AssetImporter import = AssetImporter.GetAtPath("Assets/Scene/Main.unity");//Utils.GetRelativePath(targetPath));
            AssetImporter import = AssetImporter.GetAtPath(Utils.GetRelativePath(targetPath));
            import.assetBundleName = packageName;
            import.assetBundleVariant = "lua";
            EditorUtility.SetDirty(import);
        }
    }


}

